const app = new getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    default_img: {},
    category_id: '',
    goods_list: [], //商品列表
    goods_category_list: [], //分类列表
    category_brands: [], //品牌列表
    search_text: '', //搜索内容
    category_status: 0,
    attr_or_spec: [], //属性筛选项
    goods_spec_array: [], //规格筛选项
    sort_status: 0,
    screen_status: 0,
    mask_status: 0,
    category_index: -1,
    sales_sort: 'desc',
    new_sort: 'asc',
    price_sort: 'asc',
    obyzd: '',
    sort: '',
    brand_id: '',
    min_price: '',
    max_price: '',
    new_min_price: '',
    new_max_price: '',
    screen: 0,
    attr: '',
    spec: '',
    page: 1, //页码,
    select_goods: [],
    selected_goods: [],
    searchFlag: 0,
    sortFlag: 0,
    seletCategoryFlag: 0,
    screenFlag: 0,
    addGoodsFlag: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    app.getMemberId(that, 'loadDefaultImg');

    app.sendRequest({
      url: 'System.Goods.goodsCategoryTree',
      success: function(res) {
        if (res.code == 0) {
          let goods_category_list = app.checkEmpty(res.data, []);
          that.setData({
            goods_category_list: goods_category_list
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    app.restStatus(that, 'searchFlag');
    app.restStatus(that, 'sortFlag');
    app.restStatus(that, 'seletCategoryFlag');
    app.restStatus(that, 'screenFlag');
    app.restStatus(that, 'addGoodsFlag');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.loadGoodsList();
  },

  loadDefaultImg: function () {
    let that = this;
    app.defaultImg(that, true);
  },

  /**
   * 图片加载失败
   */
  errorImg: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let goods_list = that.data.goods_list;
    let default_img = that.data.default_img;
    let base = that.data.Base;
    let parm = {};
    let img = goods_list[index].pic_cover_small;

    if (default_img.is_use == 1) {
      let default_goods_img = default_img.value.default_goods_img;
      if (img.indexOf(default_goods_img) == -1) {
        let parm_key = "goods_list[" + index + "].pic_cover_small";

        parm[parm_key] = default_goods_img;
        that.setData(parm);
      }
    }
  },


  /**
   * 输入框绑定事件
   */
  searchInput: function(event) {
    let search_text = event.detail.value;
    this.setData({
      search_text: search_text
    })
  },

  /**
   * 搜索商品
   */
  search: function(event) {
    let that = this;
    let searchFlag = that.data.searchFlag;
    let search_text = that.data.search_text;

    if (searchFlag == 1) {
      return false;
    }
    app.clicked(that, 'searchFlag');
    that.setData({
      search_text: search_text,
      page: 1,
      goods_list: []
    })
    that.loadGoodsList();
  },

  /**
   * 分类弹框
   */
  category: function(e) {
    let that = this;
    let category_status = that.data.category_status;
    category_status = category_status == 0 ? 1 : 0;
    let mask_status = category_status == 1 ? 1 : 0;


    that.setData({
      category_status: category_status,
      sort_status: 0,
      screen_status: 0,
      mask_status: mask_status
    })
  },

  /**
   * 排序弹框
   */
  sort: function(e) {
    let that = this;
    let sort_status = that.data.sort_status;
    sort_status = sort_status == 0 ? 1 : 0;
    let mask_status = sort_status == 1 ? 1 : 0;

    that.setData({
      sort_status: sort_status,
      category_status: 0,
      screen_status: 0,
      mask_status: mask_status
    })
  },

  /**
   * 筛选弹框
   */
  screen: function(e) {
    let that = this;
    let screen_status = that.data.screen_status;
    screen_status = screen_status == 0 ? 1 : 0;
    let mask_status = screen_status == 1 ? 1 : 0;

    let goods_spec_array = that.data.goods_spec_array;
    if (app.checkArray(goods_spec_array)) {
      for (let index in goods_spec_array) {
        let values = goods_spec_array[index].values;
        for (let key in values) {
          if (values[key].is_selected == 1) {
            values[key].is_select = 1;
          } else {
            values[key].is_select = 0;
          }
        }
        goods_spec_array[index].values = values;
      }
    }

    let attr_or_spec = that.data.attr_or_spec;
    if (app.checkArray(attr_or_spec)) {
      for (let index in attr_or_spec) {
        let value_items = attr_or_spec[index].value_items;
        for (let key in value_items) {
          if (value_items[key].is_selected == 1) {
            value_items[key].is_select = 1;
          } else {
            value_items[key].is_select = 0;
          }
        }
        attr_or_spec[index].value_items = value_items;
      }
    }

    that.setData({
      screen_status: screen_status,
      category_status: 0,
      sort_status: 0,
      mask_status: mask_status,
      attr_or_spec: attr_or_spec,
      goods_spec_array: goods_spec_array
    })
  },

  /**
   * 关闭弹框
   */
  closePoupo: function(e) {
    let that = this;

    that.setData({
      mask_status: 0,
      category_status: 0,
      sort_status: 0,
      screen_status: 0,
      new_min_price: '',
      new_max_price: '',
    })
  },


  /**
   * 选择分类
   */
  selectCategory: function(e) {
    let that = this;
    let dataset = e.currentTarget.dataset;
    let category_id = dataset.id;
    let category_index = dataset.index;
    let goods_category_list = that.data.goods_category_list;

    if (category_index > -1 && goods_category_list[category_index].category_id == category_id && goods_category_list[category_index].child_list.length > 0) {
      that.setData({
        category_id: category_id,
        category_index: category_index,
      })
      return false;
    }
    let seletCategoryFlag = that.data.seletCategoryFlag;
    if (seletCategoryFlag == 1) {
      return false;
    }
    app.clicked(that, 'seletCategoryFlag');

    category_id = category_id == 0 ? '' : category_id;
    
    that.setData({
      category_id: category_id,
      category_index: category_index,
      page: 1,
      goods_list: []
    })
    that.loadGoodsList();
    if (app.checkEmpty(category_id, '') != '') {
      that.loadBrandList();
      that.loadSpecList();
    }
    that.closePoupo();
  },

  /**
   * 选择排序
   */
  selectSort: function(e) {
    let that = this;
    let dataset = e.currentTarget.dataset;
    let obyzd = dataset.obyzd;
    let sort = dataset.sort;
    let category_id = that.data.category_id;
    let sales_sort = that.data.sales_sort;
    let new_sort = that.data.new_sort;
    let price_sort = that.data.price_sort;
    let brand_id = that.data.brand_id;
    let min_price = that.data.min_price;
    let max_price = that.data.max_price;
    let sortFlag = that.data.sortFlag;

    if (sortFlag == 1) {
      return false;
    }
    app.clicked(that, 'sortFlag');

    if (obyzd == 'ng.sales') {
      sales_sort = sales_sort == 'desc' ? 'asc' : 'desc';
    } else if (obyzd == 'ng.is_new') {
      new_sort = new_sort == 'desc' ? 'asc' : 'desc';
    } else if (obyzd == 'ng.promotion_price') {
      price_sort = price_sort == 'desc' ? 'asc' : 'desc';
    } else {
      sort = '';
      sales_sort = 'desc';
      new_sort = 'asc';
      price_sort = 'asc';
    }

    that.setData({
      obyzd: obyzd,
      sort: sort,
      sales_sort: sales_sort,
      new_sort: new_sort,
      price_sort: price_sort,
      page: 1,
      goods_list: []
    })
    that.loadGoodsList();
    that.closePoupo();
  },

  /**
   * 选择品牌
   */
  selectBrand: function(e) {
    let that = this;
    let dataset = e.currentTarget.dataset;
    let brand_id = dataset.id;

    that.setData({
      brand_id: brand_id
    })
  },


  /**
   * 选择属性
   */
  selectAttr: function(e) {
    let that = this;
    let id = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index;
    let attr_item = that.data.attr_or_spec[index];
    let items = attr_item.value_items;

    let k = {};
    let parm = '';
    for (let index in items) {
      if (id == index) {
        items[index].is_select = 1;
      } else {
        items[index].is_select = 0;
      }
    }
    parm = 'attr_or_spec[' + index + '].value_items';
    k[parm] = items;
    that.setData(k)
  },

  /**
   * 属性项高度改变
   */
  attrHeight: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let attr_or_spec = that.data.attr_or_spec;

    for (let key in attr_or_spec) {
      if (key == index) {
        if (attr_or_spec[key].open_height == 0) {
          attr_or_spec[key].open_height = 1;
        } else {
          attr_or_spec[key].open_height = 0;
        }
      }
    }

    that.setData({
      attr_or_spec: attr_or_spec
    })

  },

  /**
   * 规格项高度改变
   */
  specHeight: function(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let goods_spec_array = that.data.goods_spec_array;

    for (let key in goods_spec_array) {
      if (key == index) {
        if (goods_spec_array[key].open_height == 0) {
          goods_spec_array[key].open_height = 1;
        } else {
          goods_spec_array[key].open_height = 0;
        }
      }
    }

    that.setData({
      goods_spec_array: goods_spec_array
    })
  },

  /**
   * 选择规格
   */
  selectSpec: function(e) {
    let that = this;
    let id = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index;
    let attr_item = that.data.goods_spec_array[index];
    let items = attr_item.values;

    let k = {};
    let parm = '';
    for (let index in items) {
      if (id == index) {
        items[index].is_select = 1;
      } else {
        items[index].is_select = 0;
      }
    }
    parm = 'goods_spec_array[' + index + '].values';
    k[parm] = items;
    that.setData(k)
  },

  /**
   * 价格
   */
  bindKeyInput: function(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let min_price = that.data.new_min_price;
    let max_price = that.data.new_max_price;
    if (id == 'min_price') {
      min_price = e.detail.value;
    }
    if (id == 'max_price') {
      max_price = e.detail.value;
    }
    that.setData({
      new_min_price: min_price,
      new_max_price: max_price
    })
  },


  /**
   * 清除选项
   */
  clearOption: function(e) {
    let that = this;
    let attr_or_spec = that.data.attr_or_spec;
    if (app.checkArray(attr_or_spec)) {
      for (let index in attr_or_spec) {
        let value_items = attr_or_spec[index].value_items;
        for (let key in value_items) {
          if (key == 0) {
            value_items[key].is_select = 1;
          } else {
            value_items[key].is_select = 0;
          }
        }
        attr_or_spec[index].value_items = value_items;
      }
    }

    let goods_spec_array = that.data.goods_spec_array;
    if (app.checkArray(goods_spec_array)) {
      for (let index in goods_spec_array) {
        let values = goods_spec_array[index].values;
        for (let key in values) {
          if (key == 0) {
            values[key].is_select = 1;
          } else {
            values[key].is_select = 0;
          }
        }
        goods_spec_array[index].values = values;
      }
    }

    that.setData({
      goods_spec_array: goods_spec_array,
      attr_or_spec: attr_or_spec,
      min_price: null,
      max_price: null
    })

  },

  /**
   * 取消
   */
  cancel: function() {
    let that = this;
    let screen_status = 0;
    let mask_status = 0;
    that.setData({
      screen_status: screen_status,
      mask_status: mask_status
    })
  },

  /**
   * 确认
   */
  confirm: function() {
    let screenFlag = this.data.screenFlag;
    if (screenFlag == 1) {
      return false;
    }
    app.clicked(this, screenFlag);

    this.setData({
      page: 1,
      goods_list: []
    })
    this.loadGoodsList();
    this.closePoupo();
  },

  loadInfo: function() {
    this.loadGoodsList();
  },

  /**
   * 选中商品
   */
  selectGoods: function (e) {
    let is_selected = e.currentTarget.dataset.selected;
    let is_select = is_selected == 1 ? 0 : 1;
    let index = e.currentTarget.dataset.index;
    let param = {};
    let key = '';

    key = 'goods_list[' + index + '].is_select';
    param[key] = is_select;
    this.setData(param);
  },

  /**
   * 选中全部商品
   */
  selectAllGoods: function (e) {
    let is_selected = e.currentTarget.dataset.selected;
    let goods_list = this.data.goods_list;
    let is_select_all = is_selected == 1 ? 0 : 1;

    for (let index in goods_list ) {
      goods_list[index].is_select = is_select_all;
    }
    this.setData({
      goods_list: goods_list,
      is_select_all: is_select_all
    })
  },

  /**
   * 加载商品列表
   */
  loadGoodsList: function() {
    let that = this;
    let category_id = that.data.category_id;

    let params = {
      page: that.data.page,
      page_size: 10,
      uid: that.data.uid,
      category_id: category_id,
      obyzd: that.data.obyzd,
      st: that.data.sort,
      attr: that.data.attr,
      spec: that.data.spec,
      brand_id: that.data.brand_id,
      min_price: that.data.new_min_price,
      max_price: that.data.new_max_price,
      search_text: that.data.search_text
    };

    app.sendRequest({
      url: 'System.Distribution.distributionGoodsList',
      data: params,
      success: function(res) {
        console.log(res);
        if (res.code == 0) {
          let param = {};
          let key = '';

          let goods_list = app.checkEmpty(res.data.data, []);
          let length = 0;
          // 存在商品数据 调整页码
          let selected_goods = params.page == 1 ? [] : that.data.selected_goods;
          if (app.checkArray(goods_list)) {
            params.page++;
            length = that.data.goods_list.length;
          }
          let goods_category_list = that.data.goods_category_list;
          let category_index = that.data.category_index;

          for (let index in goods_category_list) {
            if (goods_category_list[index].category_id == category_id) {
              category_index = index;
            }
            let child_list = goods_category_list[index].child_list

            for (let key in child_list) {
              if (child_list[key].category_id == category_id) {
                category_index = index;
              }
            }
          }

          for (let index in goods_list) {
            let goods = goods_list[index];
            //图片处理
            let img = goods.pic_cover_small;
            goods.pic_cover_small = app.IMG(img);

            // 数据处理
            goods.goods_commission = app.checkEmpty(goods.goods_commission, {});
            goods.goods_commission.distribution_commission = app.checkEmpty(goods.goods_commission.distribution_commission, 0);
            goods.goods_commission.distribution_commission = parseFloat(goods.goods_commission.distribution_commission).toFixed(2);
            
            if (goods.is_select == 1) {
              selected_goods.push(goods.goods_id);
            }
            key = 'goods_list[' + (parseInt(length) + parseInt(index)) + ']';
            param[key] = goods;
          }

          let screen = 0;
          if (app.checkArray(goods_list) && app.checkEmpty(category_id, 0) != 0) {
            screen = 1;
          }

          param.category_index = category_index;
          param.page = params.page;
          param.selected_goods = selected_goods;
          that.setData(param)
          app.restStatus(that, 'searchFlag');
          app.restStatus(that, 'sortFlag');
          app.restStatus(that, 'seletCategoryFlag');
          app.restStatus(that, 'screenFlag');
        }
      }
    });
  },

  /**
   * 加载品牌列表
   */
  loadBrandList: function() {
    let that = this;
    let category_id = that.data.category_id;

    app.sendRequest({
      url: 'System.Goods.brandSelection',
      data: {
        category_id: category_id
      },
      success: function(res) {
        if (res.code == 0) {
          let category_brands = app.checkEmpty(res.data, []);
          that.setData({
            category_brands: category_brands
          })
        }
      }
    });
  },

  /**
   * 加载属性列表
   */
  loadAttributeList: function() {
    let that = this;
    let category_id = that.data.category_id;

    app.sendRequest({
      url: 'System.Goods.attributeSelection',
      data: {
        category_id: category_id
      },
      success: function(res) {
        if (res.code == 0) {
          let attr_or_spec = app.checkEmpty(res.data, []);

          for (let index in attr_or_spec) {
            delete attr_or_spec[index].is_search;
            delete attr_or_spec[index].type;
            delete attr_or_spec[index].sort;
            attr_or_spec[index]['open_height'] = 0;

            attr_or_spec[index].value_items = app.checkEmpty(attr_or_spec[index].value_items, []);
            attr_or_spec[index].value_items.unshift('全部')

            let spec_value = attr_or_spec[index].value_items;
            for (let key in spec_value) {
              let item_value = spec_value[key];
              spec_value[key] = {};
              spec_value[key]['value'] = item_value;
              if (key == 0) {
                spec_value[key]['is_select'] = 1;
                spec_value[key]['is_selected'] = 1;
              } else {
                spec_value[key]['is_select'] = 0;
                spec_value[key]['is_selected'] = 0;
              }
            }
            attr_or_spec[index].value_items = spec_value;
          }
          that.setData({
            attr_or_spec: attr_or_spec
          })
        }
      }
    });
  },

  /**
   * 加载规格列表
   */
  loadSpecList: function() {
    let that = this;
    let category_id = that.data.category_id;

    app.sendRequest({
      url: 'System.Goods.goodsSpecArray',
      data: {
        category_id: category_id
      },
      success: function(res) {
        if (res.code == 0) {
          let goods_spec_array = app.checkEmpty(res.data, []);
          for (let index in goods_spec_array) {
            delete goods_spec_array[index].create_time;
            delete goods_spec_array[index].show_type;
            delete goods_spec_array[index].sort;
            goods_spec_array[index]['open_height'] = 0;

            if (app.checkArray(goods_spec_array[index].values)) {
              let obj = {
                'spec_value_name': '全部'
              }
              goods_spec_array[index].values.unshift(obj)
              let spec_value = app.checkEmpty(goods_spec_array[index].values, []);
              for (let key in spec_value) {
                let item_value = spec_value[key];
                spec_value[key] = {};
                spec_value[key]['values'] = item_value;
                if (key == 0) {
                  spec_value[key]['is_select'] = 1;
                  spec_value[key]['is_selected'] = 1;
                } else {
                  spec_value[key]['is_select'] = 0;
                  spec_value[key]['is_selected'] = 0;
                  let spec_value_name = spec_value[key].values.spec_value_name;

                  let str = spec_value_name.indexOf('&nbsp;');
                  if (str) {
                    spec_value_name = spec_value_name.replace(RegExp("&nbsp;", "g"), " ");
                  }
                  spec_value[key].values.spec_value_name = spec_value_name;
                }
              }
              goods_spec_array[index].values = spec_value;
            }
          }
          that.setData({
            goods_spec_array: goods_spec_array
          })
        }
      }
    });
  },

  /**
   * 加载价格区间
   */
  loadPriceGrades: function () {
    app.sendRequest({
      url: 'System.Goods.categoryPriceGrades',
      data: {
        category_id: category_id
      },
      success: function (res) {
        if (res.code == 0) {
          let category_price_grades = app.checkEmpty(res.data, []);
          that.setData({
            category_price_grades: category_price_grades
          })
        }
      }
    });
  },

  /**
   * 添加分销商品
   */
  addGoods: function () {
    let that = this;
    let uid = that.data.uid;
    let selected_goods = that.data.selected_goods;
    let goods_list = that.data.goods_list;
    let addGoodsFlag = that.data.addGoodsFlag;
    if (addGoodsFlag == 1) {
      return false;
    }
    app.clicked(that, 'addGoodsFlag');
    
    let select_goods = [];
    for (let index in goods_list) {
      if (goods_list[index].is_select == 1) {
        select_goods.push(goods_list[index].goods_id);
      }
    }

    if (selected_goods.length != 0 && selected_goods.length == select_goods.length) {
      let different_count = 0;
      for (let key in select_goods) {
        if (selected_goods.indexOf(select_goods[key]) == -1) {
          different_count++;
          break;
        }
      }
      app.showBox(that, '所选商品已在分销商城中');
      app.restStatus(that, 'addGoodsFlag');
      return false;
    }

    let goods_id_str = select_goods.toString();
    app.sendRequest({
      url: 'System.Distribution.addPromoterGoods',
      data: {
        goods_id_str: goods_id_str
      },
      success: function (res) {
        if (res.code == 0) {
          if (res.data != '') {
            app.showBox(that, '添加成功');
            setTimeout( function (){
              wx.redirectTo({
                url: '/pagesnfx/pages/distribution/usershopgoods/usershopgoods?uid=' + uid,
              })
            }, 1500)
          } else {
            app.showBox(that, '添加失败');
            app.restStatus(that, 'addGoodsFlag');
          }
        }
      }
    });
  }
})